<template>
    <!-- fixed 固定位置，并通过 bottom-xx right-xx 设置在右下角 -->
    <div v-show="showScrollToTopBtn" @click="scrollToTop"
        class="z-50 border cursor-pointer fixed bottom-2 right-2 md:bottom-10 md:right-10 inline p-3 bg-white hover:bg-gray-100 rounded dark:bg-gray-800 dark:hover:bg-gray-900 dark:border-gray-700">
        <svg t="1730389290878" class="icon w-6 h-6 text-gray-500 dark:text-white" viewBox="0 0 1026 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
            p-id="50748" width="200" height="200">
            <path
                d="M510.770957 0.002456A510.770957 510.770957 0 1 0 1023.179001 511.182685 510.770957 510.770957 0 0 0 510.770957 0.002456z m230.829183 603.266339a31.104642 31.104642 0 0 1-22.100666-9.003975l-178.033147-178.033147v413.364317a31.104642 31.104642 0 0 1-62.209283 0V417.86876L302.451713 594.26482a31.513913 31.513913 0 1 1-45.019876-43.792062l230.419911-230.419911a31.104642 31.104642 0 0 1 45.019876 0l230.419911 230.419911a31.104642 31.104642 0 0 1-22.100667 53.205308z m29.467555-322.09675H250.474219a31.104642 31.104642 0 1 1 0-62.209283h520.593476a31.104642 31.104642 0 0 1 0 62.209283z m0 0"
                fill="#49B152" p-id="50749"></path>
        </svg>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

// 是否展示返回顶部按钮
const showScrollToTopBtn = ref(false)

// 添加滚动监听
onMounted(() => window.addEventListener('scroll', handleScroll))

// 移除滚动监听
onBeforeUnmount(() => window.removeEventListener('scroll', handleScroll))

const handleScroll = () => {
    // 如果页面滚动超过300px，显示回到顶部按钮，否则隐藏
    showScrollToTopBtn.value = window.scrollY > 300
}

// 滚动到顶部
const scrollToTop = () => {
    window.scrollTo({
        top: 0, // 距离顶部位置
        behavior: 'smooth' // 平滑滚动效果
    });
}
</script>